import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
import { resolve } from 'path'
import requireTransform from 'vite-plugin-require-transform'
import vueJsx from '@vitejs/plugin-vue2-jsx'
import envCompatible from 'vite-plugin-env-compatible'
import { viteCommonjs } from '@originjs/vite-plugin-commonjs'
import viteRequireContext from '@originjs/vite-plugin-require-context'

const pathResolve = (dir) => {
  return resolve(__dirname, '.', dir)
}

const alias = {
  '@': pathResolve('./src/'),
}
function transformScss () {
  return {
    name: 'vite-plugin-transform-scss',
    enforce: 'pre',
    transform (src, id) {
      if (
        /\.(js|ts|tsx|vue)(\?)*/.test(id) &&
        id.includes('lang.scss') &&
        !id.includes('node_modules')
      ) {
        return {
          code: src.replace(/\/deep\//gi, '::v-deep'),
        };
      }
    },
  };
}


export default defineConfig({
  plugins: [
    vue(),  // 兼容vue2.7
    vueJsx(),  // 兼容jsx语法
    envCompatible(), // 兼容process.env获取环境变量
    requireTransform({
      fileRegex: /.js$|.vue$/
    }),
    viteCommonjs(), // 兼容commonjs
    viteRequireContext(), // 兼容require.context
    transformScss(), // 兼容node-sass /deep/写法
  ],
  resolve: {
    extensions: ['.vue', '.js', '.mjs', 'jsx', '.ts', '.tsx', '.json', '.css', '.scss'],
    alias
  },
  server: {
    // open: true,
    host: '0.0.0.0',
    port: 7080,
    hmr: {
      overlay: false // 禁用 HMR 覆盖层
    },
    proxy: {
      '/api': {
        target: process.env.VITE_API_URL,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
  },
  css: {

  },
  build: {
    outDir: 'dist',
    chunkSizeWarningLimit: 1500,
    sourcemap: true,
    rollupOptions: {
      output: {
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
      },
    },
  },
  define: {
    __VUE_I18N_LEGACY_API__: JSON.stringify(false),
    __VUE_I18N_FULL_INSTALL__: JSON.stringify(false),
    __INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
    __NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
    __NEXT_NAME__: JSON.stringify(process.env.npm_package_name),
    __COMPONENT_FOLDERS__: JSON.stringify(['@/components/global', '@/custom-schema-template', '@/custom-schema-template-set/config-template', '@/custom-schema-template'])
  },
})
